package com.mcppro.aidatabase.controller;

import com.mcppro.aidatabase.dto.ChatDto;
import com.mcppro.aidatabase.entity.ChatLog;
import com.mcppro.aidatabase.service.AiChatService;
import com.mcppro.aidatabase.service.ChatLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import jakarta.validation.Valid;
import java.util.List;

/**
 * AI聊天控制器
 * 
 * @author MCP Pro
 */
@RestController
@RequestMapping("/chat")
@Validated
@Slf4j
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8081", "http://127.0.0.1:3000", "http://127.0.0.1:8081", "http://localhost", "http://127.0.0.1"}, 
             allowCredentials = "true", 
             maxAge = 3600)
public class ChatController {

    private final AiChatService aiChatService;
    private final ChatLogService chatLogService;

    @Autowired
    public ChatController(AiChatService aiChatService, ChatLogService chatLogService) {
        this.aiChatService = aiChatService;
        this.chatLogService = chatLogService;
    }

    /**
     * 主要的聊天接口
     * 
     * @param request 聊天请求
     * @return 聊天响应
     */
    @PostMapping
    public Mono<ResponseEntity<ChatDto.ChatResponse>> chat(@Valid @RequestBody ChatDto.ChatRequest request) {
        log.info("收到聊天请求 - 会话: {}, 问题: {}", request.getSessionId(), request.getQuestion());
        
        return aiChatService.processChat(request)
                .map(response -> {
                    log.info("聊天响应完成 - 会话: {}, 成功: {}, 耗时: {}ms", 
                            response.getSessionId(), response.isSuccess(), response.getTotalExecutionTime());
                    
                    if (response.isSuccess()) {
                        return ResponseEntity.ok(response);
                    } else {
                        return ResponseEntity.badRequest().body(response);
                    }
                })
                .onErrorResume(error -> {
                    log.error("聊天处理异常", error);
                    ChatDto.ChatResponse errorResponse = ChatDto.ChatResponse.failure(
                            "服务器内部错误: " + error.getMessage(),
                            request.getSessionId()
                    );
                    return Mono.just(ResponseEntity.internalServerError().body(errorResponse));
                });
    }

    /**
     * 获取聊天历史
     * 
     * @param sessionId 会话ID
     * @return 聊天历史记录
     */
    @GetMapping("/history/{sessionId}")
    public ResponseEntity<List<ChatLog>> getChatHistory(@PathVariable String sessionId) {
        log.debug("获取聊天历史 - 会话: {}", sessionId);
        
        try {
            List<ChatLog> history = chatLogService.getChatHistory(sessionId);
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            log.error("获取聊天历史失败 - 会话: {}", sessionId, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取最近的聊天记录
     * 
     * @param limit 限制数量
     * @return 最近的聊天记录
     */
    @GetMapping("/recent")
    public ResponseEntity<List<ChatLog>> getRecentChats(@RequestParam(defaultValue = "20") int limit) {
        log.debug("获取最近聊天记录 - 限制: {}", limit);
        
        try {
            List<ChatLog> recentChats = chatLogService.getRecentChats(limit);
            return ResponseEntity.ok(recentChats);
        } catch (Exception e) {
            log.error("获取最近聊天记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取聊天统计信息
     * 
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<ChatLogService.ChatStatistics> getChatStatistics() {
        log.debug("获取聊天统计信息");
        
        try {
            ChatLogService.ChatStatistics statistics = chatLogService.getChatStatistics();
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("获取聊天统计信息失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 清除会话历史
     * 
     * @param sessionId 会话ID
     * @return 操作结果
     */
    @DeleteMapping("/history/{sessionId}")
    public ResponseEntity<String> clearChatHistory(@PathVariable String sessionId) {
        log.info("清除聊天历史 - 会话: {}", sessionId);
        
        try {
            chatLogService.clearSessionHistory(sessionId);
            return ResponseEntity.ok("聊天历史清除成功");
        } catch (Exception error) {
            log.error("清除聊天历史失败 - 会话: {}", sessionId, error);
            return ResponseEntity.internalServerError().body("清除聊天历史失败: " + error.getMessage());
        }
    }

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        return ResponseEntity.ok("Chat service is running");
    }
}